package com.twu.biblioteca;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class userStore {
    private Map<String,userInstance> currentUsers;
    BufferedReader bufferRead;
    userInstance currentLoggedinUser;
    public userStore(){
        currentUsers = new HashMap<String, userInstance>(20);
        bufferRead = new BufferedReader(new InputStreamReader(System.in));
    }
    public void addUser(userInstance nextUser){
        currentUsers.put(nextUser.getUsername(),nextUser);
    }

    public userInstance getUser(String idToSearch){
        return currentUsers.get(idToSearch);
    }

    public boolean doLogin() throws IOException {
        boolean answer;
        String choice;
        do{
            answer = validateCredentials();
            if(!answer){
                System.out.print("Invalid login/ Login Again Yes?No");
                choice = bufferRead.readLine();
                if (choice.contains("y")||choice.contains("Y"))continue;
                else break;
            }
            else
                break;
        }while (true);
        return answer;
    }
    public boolean validateCredentials() throws IOException {
        System.out.print("Enter username");
        String userName = bufferRead.readLine();
        if(currentUsers.containsKey(userName)){
            System.out.print("Enter Password");
            String passWord = bufferRead.readLine();
            if(passWord.matches(currentUsers.get(userName).getPassword())){
                currentLoggedinUser = currentUsers.get(userName);
                return true;
            }
            else
                System.out.print("Invalid Password\n");
                return false;
        }
        else{
            System.out.print("Invalid Username\n");
            return false;
        }
    }
    public userInstance getLoggedInUser(){
        return currentLoggedinUser;
    }
}
